<template>
  <div style="margin-top: 60px; margin-left: 330px; width: 300px; height: 500px;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="ID">
        <el-input v-model="ruleForm.id" readonly></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="介绍" prop="introduction">
        <el-input v-model="ruleForm.introduction"></el-input>
      </el-form-item>
      <el-form-item label="管理员" prop="adminId">
        <el-select v-model="ruleForm.adminId" placeholder="请选择管理员">
          <el-option
            v-for="item in dormitoryAdminList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即修改</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      ruleForm: {
        id: '',
        name: '',
        introduction: '',
        adminId: ''
      },
      dormitoryAdminList: [],
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        introduction: [{ required: true, message: '请输入介绍', trigger: 'blur' }],
        adminId: [{ required: true, message: '请选择管理员', trigger: 'change' }]
      }
    }
  },
  methods: {
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const resp = await axios.put('http://localhost:8181/building/update', this.ruleForm)
            if (resp.data.code === 0) {
              this.$alert(`${this.ruleForm.name} 修改成功`, '提示', {
                confirmButtonText: '确定',
                callback: () => {
                  this.$router.push('/buildingManager')
                }
              })
            } else {
              this.$message.error(resp.data.message || '修改失败')
            }
          } catch (error) {
            this.$message.error('请求失败: ' + error.message)
          }
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    async loadData() {
      try {
        const id = this.$route.query.id
        const [adminRes, buildingRes] = await Promise.all([
          axios.get('http://localhost:8181/dormitoryAdmin/list'),
          axios.get(`http://localhost:8181/building/findById/${id}`)
        ])
        this.dormitoryAdminList = adminRes.data.data || []
        this.ruleForm = buildingRes.data.data || {}
      } catch (error) {
        this.$message.error('加载数据失败: ' + error.message)
      }
    }
  },
  created() {
    this.loadData()
  }
}
</script>
